package com.bigShen.mybatis.proxy;

import com.bigShen.mybatis.session.SqlSessionShen;
import com.bigShen.mybatis.util.SqlCommandType;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Author eddy.shen
 * @Date 2018/12/8 21:07
 **/
public class MapperProxyShen<T> implements InvocationHandler {

    private final SqlSessionShen sqlSession;

    private final Class<T> mapperInterface;

    public MapperProxyShen(SqlSessionShen sqlSession, Class<T> mapperInterface) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        try {
            if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this, args);
            }
        } catch (Throwable t) {
            throw t;
        }


        MapperMethod mapperMethod = cachedMapperMethod(method);
        //return sqlSession.getExecutor().selectOne(sql, args[0]);
        return mapperMethod.execute(sqlSession, args);
    }

    public MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = new MapperMethod();
        String selectId = String.format("%s.%s", method.getDeclaringClass().getName(), method.getName());
        SqlCommandType sqlCommandType = sqlSession.getConfiguration().getSqlCommandType(selectId);
        if (null == sqlCommandType) {
            throw new RuntimeException("Unknown sqlCommandType form xml configuration " + selectId);
        }
        mapperMethod.setSqlCommand(new MapperMethod.SqlCommand(selectId, sqlCommandType));
        return  mapperMethod;
    }




}
